/*
 * Copyright 2010 Electronic Business Systems Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package gr.ebs.gssdroid.activities;

import gr.ebs.gssdroid.GssDroid;
import gr.ebs.gssdroid.GssDroidApplication;
import gr.ebs.gssdroid.R;
import gr.ebs.gssdroid.async.GssTaskObserver;
import gr.ebs.gssdroid.async.GssTasks;
import gr.ebs.gssdroid.async.TaskResult;
import gr.ebs.gssdroid.http.GssHttpException;
import gr.ebs.gssdroid.http.SystemErrorException;
import gr.ebs.gssdroid.resource.BackResource;
import gr.ebs.gssdroid.resource.FileResource;
import gr.ebs.gssdroid.resource.FolderResource;
import gr.ebs.gssdroid.resource.RestResource;
import gr.ebs.gssdroid.resource.UserResource;
import gr.ebs.gssdroid.util.Clipboard;
import gr.ebs.gssdroid.util.ClipboardItem;
import gr.ebs.gssdroid.widget.CustomListAdapter;
import gr.ebs.gssdroid.widget.CustomListView;
import gr.ebs.gssdroid.widget.InfoDialog;
import gr.ebs.gssdroid.widget.MyFoldersListAdapter;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.webkit.MimeTypeMap;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

public class GssMyFolders extends AbstractGssActivity implements AdapterView.OnItemClickListener, GssTaskObserver {

	public static final int MENU_HOME = Menu.FIRST;
	public static final int MENU_LOGIN = Menu.FIRST + 1;
	public static final int MENU_INFO = Menu.FIRST + 2;
	public static final int MENU_NEW = Menu.FIRST + 3;
	UserResource userResource;
	protected GssTasks tasks;
	
	protected int getContentLayoutId(){
		return R.layout.myfolders;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, MENU_HOME, 0, "Home").setIcon(android.R.drawable.btn_star);
		menu.add(0, MENU_LOGIN, 0, "Login").setIcon(android.R.drawable.ic_menu_more);
		menu.add(0, MENU_INFO, 0, "About").setIcon(android.R.drawable.ic_menu_info_details);
		menu.add(0, MENU_NEW, 0, "Create").setIcon(android.R.drawable.ic_menu_add);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_HOME:
			if(((GssDroid)getParent()).getSelectedTab()==0){
				getTasks().getFolderTask(GssMyFolders.this).execute(getDroidApplication().getUserResource().getFilesPath());
			}
			else
				((GssDroid)getParent()).selectTab(0);
			
			return true;
		case MENU_LOGIN:
			handleLogin();
			return true;
		case MENU_INFO:
			InfoDialog info = new InfoDialog(this, R.string.infodialog_title, R.string.infodialog_content);
			info.show();
			return true;
		case MENU_NEW:
			newFile();
			return true;
		}
		return super.onOptionsItemSelected( item);
	}

	MyFoldersListAdapter adapter;
	public ProgressDialog myprogress;
	Handler progresshandler;
	FolderResource currentResource;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(getContentLayoutId());
		
		
		tasks = new GssTasks(this, getDroidApplication().getUserDetails(), myprogress);
		final CustomListView mListView = ((CustomListView) findViewById(R.id.fileListView));

		mListView.setSelected(true);

		mListView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_INSET);

		// mListView.setLongClickable(true);
		// mListView.setClickable(true);

		// mListView.setFastScrollEnabled(true);
		// mListView.setScrollingCacheEnabled(true);
		mListView.setOnItemClickListener(this);
		// mListView.setItemsCanFocus(true);

		initialize();
		// AndGss.BASE_REST_URL + details.getUsername() + "/files/");

		Animation animation = AnimationUtils.loadAnimation(this, R.anim.itemanimation);

		LayoutAnimationController controller = new LayoutAnimationController(animation, 0.5f);

		mListView.setLayoutAnimation(controller);
		registerForContextMenu(mListView);
		ImageButton newButton = (ImageButton) findViewById(R.id.newBottomItem);
		newButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				newFile();
			}
		});
		ImageButton refreshButton = (ImageButton) findViewById(R.id.refreshFolder);
		refreshButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				refresh();
			}
		});
		Button chooseButton = (Button) findViewById(R.id.choose);
		if(getIntent().getExtras()!=null&&getIntent().getExtras().get("content")!=null){
			
			ArrayList l = (ArrayList) getIntent().getExtras().get("content");
			final List<Uri> uris = new ArrayList<Uri>();
			for (int i=0; i < l.size(); i++) {
				
			    final Uri curStream = (Uri) l.get(i);
			    if(curStream!=null){
			    	//showErrorDialog("received data", "data:"+l.size()+" "+curStream.getPath());
			    	uris.add(curStream);
			    }
			}
			if(uris.size()>0){
				chooseButton.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						uploadFile(uris);
					}
				});
			}
			
		}
		else
			chooseButton.setVisibility(View.INVISIBLE);
	}

	protected void initialize() {
		adapter = new MyFoldersListAdapter((Activity) this, R.layout.row, new ArrayList<RestResource>()) {
			public void onItemClick(final int position, final View v) {
				RestResource entry = getAdapter().getItem(position);
				RestResource toUse = entry;

				Intent intent = new Intent(getApplication(), GssProperties.class);
				intent.putExtra("resource", toUse);
				startActivityForResult(intent, 2009);

			};
		};

		((CustomListView) findViewById(R.id.fileListView)).setAdapter(adapter);
		if(getDroidApplication().getUserResource()==null||getDroidApplication().getUserResource().getFilesPath()==null){
			handleLogin();
			finish();
			return;
		}
		Log.d("INIT:", ""+getDroidApplication());
		Log.d("INIT2:", ""+getDroidApplication());
		getTasks().getHomeFolderTask(GssMyFolders.this).execute(getDroidApplication().getUserResource().getFilesPath());
	}

	private void animation() {
		Animation animation = AnimationUtils.loadAnimation(this, R.anim.itemanimation);

		LayoutAnimationController controller = new LayoutAnimationController(animation, 0.5f);

		((CustomListView) findViewById(R.id.fileListView)).setLayoutAnimation(controller);

	}

	protected void onEntrySelected(int position, final RestResource resource) {
		if (resource instanceof FolderResource || resource instanceof BackResource) {
			String pathToGet = resource.getUri();
			getTasks().getFolderTask(GssMyFolders.this).execute(pathToGet);
		} else if (resource instanceof FileResource) {
			long filesize = ((FileResource) resource).getContentLength();
			if (filesize > 5000000L) {
				AlertDialog alertDialogn = new AlertDialog.Builder(this).create();
				alertDialogn.setTitle("Large file size");
				alertDialogn.setMessage("File size is too large are you sure you want to proceed with download?");
				alertDialogn.setButton("Continue", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						getTasks().getFileTask(GssMyFolders.this).execute(((FileResource) resource).getUri());
						dialog.dismiss();
					}
				});
				alertDialogn.setButton2("Cancel", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				alertDialogn.setCancelable(true);
				alertDialogn.show();
			} else {
				getTasks().getFileTask(GssMyFolders.this).execute(((FileResource) resource).getUri());
			}
		}

	}

	protected void populateList(RestResource resource) {
		((TextView) findViewById(R.id.textPath)).setText(((FolderResource) resource).getName() + " files");
		ArrayList<RestResource> data = new ArrayList<RestResource>();
		if (resource.getUri().equals(getDroidApplication().getUserResource().getFilesPath()) || resource.getUri().equals(getDroidApplication().getUserResource().getFilesPath() + "/")) {
		} else {
			data.add(new BackResource(((FolderResource) resource).getParentURI(), ((FolderResource) resource).getParentName(), FolderResource.class, currentResource));
		}
		currentResource = (FolderResource) resource;

		data.addAll(((FolderResource) resource).getFolders());
		for(FileResource r : ((FolderResource) resource).getFiles())
			if(!r.isDeleted())
				data.add(r);
		adapter.setListItems(data);
		adapter.notifyDataSetChanged();
		animation();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		onEntrySelected(arg2, adapter.getItem(arg2));
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		MenuInflater inflater = getMenuInflater();
		final RestResource entry = getAdapter().getItem(((AdapterContextMenuInfo) menuInfo).position);
		if (entry instanceof BackResource){
			if(!((GssDroidApplication)getApplication()).getClipboard().hasFolderOrFileItem()){
				return;
			}
			else{
				inflater.inflate(R.menu.foldercontextmenu, menu);
				for (int i = 0; i < menu.size(); i++) {
					menu.getItem(i).setVisible(false);
				}
				menu.findItem(R.id.paste).setVisible(((GssDroidApplication)getApplication()).getClipboard().hasFolderOrFileItem());
				return;
			}
		}
		inflater.inflate(R.menu.foldercontextmenu, menu);
		if (entry instanceof FolderResource){
			menu.findItem(R.id.download).setVisible(false);
			menu.findItem(R.id.versions).setVisible(false);
			menu.findItem(R.id.paste).setVisible(((GssDroidApplication)getApplication()).getClipboard().hasFolderOrFileItem());
		}
		else
			menu.findItem(R.id.download).setVisible(true);
		if(entry instanceof FileResource)
			menu.findItem(R.id.versions).setVisible(true);
		menu.findItem(R.id.restoreFolder).setVisible(false);
		/*
		 * AdapterView.AdapterContextMenuInfo info =
		 * (AdapterView.AdapterContextMenuInfo) menuInfo; GssFileListAdapter
		 * adapt = (GssFileListAdapter) ((GssFileListView)
		 * findViewById(R.id.fileListView)) .getAdapter(); final
		 * GssFileListAdapterEntry entry = adapt.getItem(info.position); //
		 * if(entry.file instanceof FolderResource)
		 */

	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
		AlertDialog alertDialog = null;
		final RestResource entry = getAdapter().getItem(info.position);
		switch (item.getItemId()) {
		
		case R.id.deleteFolder:
			alertDialog = new AlertDialog.Builder(this).create();
			if(entry instanceof FolderResource){
				alertDialog.setTitle("Delete Folder");
				alertDialog.setMessage("R u sure you want to delete this folder and all its children?");
			}
			else if(entry instanceof FileResource){
				alertDialog.setTitle("Delete File");
				alertDialog.setMessage("R u sure you want to delete this file?");
			}
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					getTasks().deleteFolderTask(GssMyFolders.this).execute(entry.getUri());
				}
			});
			alertDialog.setButton2("CANCEL", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

				}
			});
			alertDialog.setCancelable(true);
			alertDialog.show();
			return true;
		case R.id.trashFolder:
			alertDialog = new AlertDialog.Builder(this).create();
			if(entry instanceof FolderResource){
				alertDialog.setTitle("Move Folder to trash");
				alertDialog.setMessage("R u sure you want to trash this folder and all its children?");
			}
			else if(entry instanceof FileResource){
				alertDialog.setTitle("Move file to trash");
				alertDialog.setMessage("R u sure you want to trash this file?");
			}
			alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					getTasks().trashFolderTask(GssMyFolders.this).execute(entry.getUri());
				}
			});
			alertDialog.setButton2("CANCEL", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

				}
			});
			alertDialog.setCancelable(true);
			alertDialog.show();
			return true;
		case R.id.properties:
			RestResource toUse = entry;
			Intent intent = new Intent(getApplication(), GssProperties.class);
			intent.putExtra("resource", toUse);
			startActivityForResult(intent, 2009);

			return true;
		case R.id.versions:
			RestResource toUseV = entry;
			Intent intentv = new Intent(getApplication(), GssVersions.class);
			intentv.putExtra("resource", toUseV);
			startActivityForResult(intentv, 2010);

			return true;
		case R.id.download:
			getTasks().getFileTask(GssMyFolders.this).execute(((FileResource) entry).getUri());
			return true;
		 case R.id.copy:
			 ((GssDroidApplication)getApplication()).getClipboard().clear();
			 if(entry instanceof FolderResource){
				 ((GssDroidApplication)getApplication()).getClipboard().setItem(new ClipboardItem((FolderResource)entry));
			 }
			 else if(entry instanceof FileResource){
				 ((GssDroidApplication)getApplication()).getClipboard().setItem(new ClipboardItem((FileResource)entry));
			 }
			 return true;
		 case R.id.cut:
			 ((GssDroidApplication)getApplication()).getClipboard().clear();
			 if(entry instanceof FolderResource){
				 ((GssDroidApplication)getApplication()).getClipboard().setItem(new ClipboardItem(Clipboard.CUT,(FolderResource)entry));
			 }
			 else if(entry instanceof FileResource){
				 ((GssDroidApplication)getApplication()).getClipboard().setItem(new ClipboardItem(Clipboard.CUT,(FileResource)entry));
			 }
			 return true;
		 case R.id.paste:
			 ClipboardItem citem = ((GssDroidApplication)getApplication()).getClipboard().getItem();
			 String target = currentResource.getUri();
			 target = target.endsWith("/") ? target : target + '/';
			 
			 String source="";
			 if(citem.getFolderResource()!=null){
				 source = citem.getFolderResource().getUri();
				 target = target + URLEncoder.encode(citem.getFolderResource().getName());
				 if(citem.getOperation()==Clipboard.CUT)
					 getTasks().getPasteTask(GssMyFolders.this).execute("cut",citem.getFolderResource().getUri(),target);
				 else if(citem.getOperation()==Clipboard.COPY)
					 getTasks().getPasteTask(GssMyFolders.this).execute("copy",citem.getFolderResource().getUri(),target);
			 }
			 else if(citem.getFile()!=null){
				 source = citem.getFile().getUri();
				 target = target + URLEncoder.encode(citem.getFile().getName());
				 if(citem.getOperation()==Clipboard.CUT)
					 getTasks().getPasteTask(GssMyFolders.this).execute("cut",citem.getFile().getUri(),target);
				 else if(citem.getOperation()==Clipboard.COPY)
					 getTasks().getPasteTask(GssMyFolders.this).execute("copy",citem.getFile().getUri(),target);
			 }
		case R.id.quit:

			return true;
		default:
			return super.onContextItemSelected(item);
		}
	}

	private void openFile() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setData(Uri.parse("file://"));
		intent.setType("*/*");
		try {
			int i = 1;
			startActivityForResult(intent, i);

		} catch (ActivityNotFoundException e) {
			Toast.makeText(this, "No File Manager", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 2009 && resultCode == RESULT_OK) {
			refresh();
			return;
		}
		if (resultCode != RESULT_CANCELED) {
			if (requestCode == 1) {
				String filename = data.getDataString();
				uploadFile(filename, data);
			}
		}
	}
	
	protected void uploadFile(String filename, Intent data){
		if (filename.startsWith("file://")) {
			filename = filename.substring(7);
		}
		// replace %20 and so on
		filename = Uri.decode(filename);

		int indx = filename.lastIndexOf("//");
		File file = new File(data.getData().getPath());
		String filenameNew = null;
		Long fileSize = null;
		if (!file.exists()) {
			Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
			if (cursor != null) {
				while (cursor.moveToNext()) {
					for (int i = 0; i < cursor.getColumnCount(); i++) {
						if (cursor.getColumnName(i).equals("_data"))
							filenameNew = cursor.getString(i);
						if (cursor.getColumnName(i).equals("_size"))
							fileSize = cursor.getLong(i);
					}
				}
			}
		} else {
			filenameNew = data.getData().getPath();
		}
		if (filenameNew != null) {
			file = new File(filenameNew);
			getTasks().getUploadTask(GssMyFolders.this).execute(getCurrentResource().getUri() + URLEncoder.encode(file.getName()), filenameNew);
		}
	}
	
	protected void uploadFile(List<Uri> uris){
		List<String> strings = new ArrayList<String>();
		String path = getCurrentResource().getUri();
		if(!path.endsWith("/"))
			path = path+"/";
		
		for(Uri data : uris){
			String filename = data.getPath();
			if (filename.startsWith("file://")) {
				filename = filename.substring(7);
			}
			// replace %20 and so on
			filename = Uri.decode(filename);

			int indx = filename.lastIndexOf("//");
			File file = new File(filename);
			String filenameNew = null;
			Long fileSize = null;
			if (!file.exists()) {
				Cursor cursor = getContentResolver().query(data, null, null, null, null);
				if (cursor != null) {
					while (cursor.moveToNext()) {
						for (int i = 0; i < cursor.getColumnCount(); i++) {
							if (cursor.getColumnName(i).equals("_data"))
								filenameNew = cursor.getString(i);
							if (cursor.getColumnName(i).equals("_size"))
								fileSize = cursor.getLong(i);
						}
					}
				}
			} else {
				filenameNew = data.getPath();
			}
			if (filenameNew != null) {
				file = new File(filenameNew);
				strings.add(path+URLEncoder.encode(file.getName()));
				strings.add(filenameNew);
			}
		}
		Log.i("*******",""+strings.size());
		getTasks().getMultiUploadTask(this).execute(strings.toArray(new String[strings.size()]));
			
		
	}
	protected void uploadFile(Uri data){
		String filename = data.getPath();
		if (filename.startsWith("file://")) {
			filename = filename.substring(7);
		}
		// replace %20 and so on
		filename = Uri.decode(filename);

		int indx = filename.lastIndexOf("//");
		File file = new File(filename);
		String filenameNew = null;
		Long fileSize = null;
		if (!file.exists()) {
			Cursor cursor = getContentResolver().query(data, null, null, null, null);
			if (cursor != null) {
				while (cursor.moveToNext()) {
					for (int i = 0; i < cursor.getColumnCount(); i++) {
						if (cursor.getColumnName(i).equals("_data"))
							filenameNew = cursor.getString(i);
						if (cursor.getColumnName(i).equals("_size"))
							fileSize = cursor.getLong(i);
					}
				}
			}
		} else {
			filenameNew = data.getPath();
		}
		if (filenameNew != null) {
			file = new File(filenameNew);
			String path = getCurrentResource().getUri();
			if(!path.endsWith("/"))
				path = path+"/";
			getTasks().getUploadTask(GssMyFolders.this).execute(path + URLEncoder.encode(file.getName()), filenameNew);
		}
		
	}

	protected CustomListAdapter<RestResource> getAdapter() {
		return adapter;
	}

	protected void refresh() {
		getTasks().getFolderTask(GssMyFolders.this).execute(currentResource.getUri());
	}

	protected void newFile() {
		final CharSequence[] items = { "New Folder", // "New File",
		"Upload" };
		AlertDialog.Builder builder = new AlertDialog.Builder(GssMyFolders.this);
		builder.setTitle("Create ...");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {
				switch (item) {
				case 0:
					final AlertDialog.Builder alert = new AlertDialog.Builder(GssMyFolders.this);
					alert.setTitle("New Folder");
					final EditText input = new EditText(GssMyFolders.this);
					alert.setView(input);
					alert.setPositiveButton("Create", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							String value = input.getText().toString().trim();
							getTasks().getNewFolderTask(GssMyFolders.this).execute(getCurrentResource().getUri(), value);
						}
					});

					alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							dialog.cancel();
						}
					});
					alert.show();
					break;
				case 1:
					openFile();
					break;
				case 2:
					openFile();
					break;
				default:
					break;
				}
			}
		});
		AlertDialog alert = builder.create();
		alert.show();
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		if (getAdapter().getCount() > 0 && getAdapter().getItem(0) instanceof BackResource) {
			getTasks().getFolderTask(GssMyFolders.this).execute(getAdapter().getItem(0).getUri());
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public void handleResult(int taskId, TaskResult result) {
		if (result.getException() != null && result.getException() instanceof SystemErrorException) {
			// todo
		}
		switch (taskId) {
		case GssTasks.TASK_NEWFOLDER:
			if (result.getException() == null)
				refresh();
			else if (result.getStatusCode() == 405) {
				if (((GssHttpException) result.getException()).getHeaderValue() != null)
					showErrorDialog("Duplicate Folder Name", "A folder with the same name already exists.");
				else
					showErrorDialog("No permission", "You dont have permissions to create a folder.");
			} else
				handleRestException("GET", result.getException());
			break;
		case GssTasks.TASK_DELETE:
			if (result.getException() == null)
				refresh();
			else
				handleRestException("DELETE", result.getException());
			break;
		case GssTasks.TASK_DOWNLOAD:
			if (result.getException() != null)
				handleRestException("DOWNLOAD", result.getException());
			else {
				NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
				long SIMPL = System.currentTimeMillis();
				final Notification notifyDetails = new Notification(R.drawable.icon, "", SIMPL);
				Context context = getApplicationContext();
				CharSequence contentTitle = "File " + new File(result.getResource().getUri()).getName() + " downloaded...";
				CharSequence contentText = "Open file by clicking me";
				Intent notifyIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.fromFile(new File(result.getResource().getUri())));
				
				String ext = MimeTypeMap.getSingleton().getFileExtensionFromUrl(result.getResource().getUri());
				String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);

				if (mime != null)
					notifyIntent.setDataAndType(Uri.fromFile(new File(result.getResource().getUri())), mime);
				
				PendingIntent intent = PendingIntent.getActivity(context, 0, notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);

				notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);
				notifyDetails.flags|=Notification.FLAG_AUTO_CANCEL;
				notificationManager.notify(100, notifyDetails);
				
				Intent viewIntent = new Intent(android.content.Intent.ACTION_VIEW, Uri.fromFile(new File(result.getResource().getUri())));
				String extv = MimeTypeMap.getSingleton().getFileExtensionFromUrl(result.getResource().getUri());
				String mimev = MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
				if (mimev != null)
					viewIntent.setDataAndType(Uri.fromFile(new File(result.getResource().getUri())), mime);
				try{
					startActivity(viewIntent);
				}
				catch(ActivityNotFoundException e){
					showErrorDialog("No Activity Found", "There is no activity to open this file.\nThe file is downloaded to your sdcard");
				}

			}
			break;
		case GssTasks.TASK_GETFOLDER:
			if (result.getResource() != null)
				populateList((FolderResource) result.getResource());
			else if (result.getException() != null)
				handleRestException("TRASH", result.getException());
			break;
		case GssTasks.TASK_GETHOMEFOLDER:
			if (result.getResource() != null)
				populateList((FolderResource) result.getResource());
			else if (result.getException() != null)
				if (result.getException() instanceof GssHttpException && ((GssHttpException) result.getException()).getStatusCode() ==404){
					showErrorDialog("You need to activate your account", "You have received an activation email.\nActivate your account and restart the application.", true);
				}
				else
					handleRestException("TRASH", result.getException());
			break;
		case GssTasks.TASK_MOVETOTRASH:
			if (result.getException() == null)
				refresh();
			else
				handleRestException("TRASH", result.getException());
			break;
		case GssTasks.TASK_PASTE:
			if (result.getException() == null)
				refresh();
			else
				handleRestException("PASTE", result.getException());
			break;
		case GssTasks.TASK_UPLOAD:
			if (result.getException() == null)
				refresh();
			else
				handleRestException("UPLOAD", result.getException());
			break;
		case GssTasks.TASK_MULTIUPLOAD:
			if (result.getException() == null){				
				refresh();
				Button button = (Button)findViewById(R.id.choose);
				button.setText("Exit");
				button.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						GssMyFolders.this.finish();
						
					}
				});
			}
			else
				handleRestException("UPLOAD", result.getException());
			break;
		default:
			break;
		}

	}
	public RestResource getCurrentResource() {
		return currentResource;
	}
	public GssTasks getTasks() {
		return tasks;
	}
	
	protected void showErrorDialog(String title, String message, final boolean exit){
		AlertDialog alertDialogn = new AlertDialog.Builder(this).create();
		alertDialogn.setTitle(title);
		alertDialogn.setMessage(message);
		alertDialogn.setButton("Continue",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						if(exit)
							((GssDroid)GssMyFolders.this.getParent()).finish();
					}
				});
		alertDialogn.setCancelable(true);
		alertDialogn.show();
	}
}
